import { getCanvasByTiff, createShader, createProgram, createTexture } from "./util";
import fragmentShaderSource from "./shaders/draw.frag.glsl?raw";
import vertexShaderSource from "./shaders/draw.vert.glsl?raw";
import { LayerConfig, addLayer, LayerType, removeLayer } from "../layer/layerManage.ts";
import { getLayerManagerState } from "../layer/layerManagerState.ts";
// 雷达图层管理
let layer: LayerConfig;
// 存储成熟，属性变量的位置
let wrapper: any = null;
// 存储矩形坐标
let rect = [];
// 缓冲区管理
let buffers: WebGLBuffer | null = null;
// canvas管理
let canvasData: HTMLImageElement[] = [];
// 雷达阈值
const thresholds = new Float32Array([
  0.0, 3.0, 8.0, 14.0, 20.0, 26.0, 32.0, 36.0, 40.0, 44.0, 48.0, 52.0, 56.0, 60.0, 64.0, 68.0, 100.0, 101.0
]);
const colors = new Float32Array([
  40 / 255,
  16 / 255,
  158 / 255,
  0 / 255,
  40 / 255,
  16 / 255,
  158 / 255,
  20 / 255,
  40 / 255,
  16 / 255,
  158 / 255,
  100 / 255,
  0 / 255,
  101 / 255,
  154 / 255,
  180 / 255,
  0 / 255,
  144 / 255,
  147 / 255,
  220 / 255,
  0 / 255,
  179 / 255,
  125 / 255,
  240 / 255,
  117 / 255,
  208 / 255,
  89 / 255,
  255 / 255,
  220 / 255,
  220 / 255,
  30 / 255,
  255 / 255,
  244 / 255,
  202 / 255,
  8 / 255,
  255 / 255,
  245 / 255,
  168 / 255,
  24 / 255,
  255 / 255,
  236 / 255,
  130 / 255,
  63 / 255,
  255 / 255,
  205 / 255,
  75 / 255,
  7 / 255,
  255 / 255,
  182 / 255,
  45 / 255,
  100 / 255,
  255 / 255,
  156 / 255,
  16 / 255,
  109 / 255,
  255 / 255,
  125 / 255,
  0 / 255,
  108 / 255,
  255 / 255,
  92 / 255,
  0 / 255,
  100 / 255,
  255 / 255,
  0 / 255,
  0 / 255,
  0 / 255,
  255 / 255,
  0 / 255,
  0 / 255,
  0 / 255,
  0 / 255
]);
// 动画因子
let animationFactor = 0.0;
// 动画轮播
let animationNeed = true;

// 纹理数组
let textures: WebGLTexture[] = [];

// 雷达阈值 可调范围
let thresholdsStart = 0;
let thresholdsEnd = 18;
// 雷达管理

// 初始化图层
export function initLayer(map: any, id: string, coordinate: any) {
  layer = {
    id,
    type: LayerType.custom,
    renderingMode: "2d",
    onAdd: function (map: any, gl: any) {
      // 创建、编译顶点着色器
      const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
      const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
      if (!vertexShader || !fragmentShader) {
        console.error("Failed to create shaders");
        return;
      }
      // 创建着色器程序
      wrapper = createProgram(gl, vertexShader, fragmentShader);
      if (!wrapper) {
        console.error("Failed to create shader program");
        return;
      }

      // 存储四个角用于定义一个矩形
      rect = coordinate.map((item: any[]) => {
        return mapboxgl.MercatorCoordinate.fromLngLat({ lng: item[0], lat: item[1] });
      });

      // 创建缓冲区
      buffers = gl.createBuffer();
      if (!buffers) {
        console.error("Failed to create buffer");
        return;
      }
      gl.bindBuffer(gl.ARRAY_BUFFER, buffers);
      gl.bufferData(
        gl.ARRAY_BUFFER,
        new Float32Array([
          rect[0].x,
          rect[0].y,
          rect[0].z,
          0,
          0,
          rect[1].x,
          rect[1].y,
          rect[1].z,
          1,
          0,
          rect[3].x,
          rect[3].y,
          rect[3].z,
          1,
          1,
          rect[2].x,
          rect[2].y,
          rect[2].z,
          0,
          1
        ]),
        gl.STATIC_DRAW
      );

      // 开始动画循环
      function animate() {
        map.triggerRepaint();
        requestAnimationFrame(animate);
      }
      animate();
    },
    render: function (gl: any, matrix: any) {
      if (!wrapper) {
        return;
      }

      // 判断是否有两张及以上的 TIFF 文件
      const hasTwoTextures = canvasData.length > 1;

      // 释放旧纹理
      textures.forEach(texture => {
        if (texture) {
          gl.deleteTexture(texture);
        }
      });
      textures = [];

      if (hasTwoTextures) {
        textures[0] = createTexture(gl, canvasData[0], 0);
        textures[1] = createTexture(gl, canvasData[1], 1);
      } else if (canvasData.length > 0) {
        textures[0] = createTexture(gl, canvasData[0], 0);
      }

      // 指定使用的着色器程序
      gl.useProgram(wrapper.program);
      // 传递矩阵统一变量
      gl.uniformMatrix4fv(wrapper.u_matrix, false, matrix);

      // 设置是否有两个纹理的统一变量
      gl.uniform1i(wrapper.hasTwoTextures, hasTwoTextures ? 1 : 0);

      if (textures[0]) {
        // 激活并绑定纹理 0
        gl.activeTexture(gl.TEXTURE0);
        gl.bindTexture(gl.TEXTURE_2D, textures[0]);
        // 设置着色器中的 u_image0 统一变量为纹理单元 0
        gl.uniform1i(wrapper.u_image0, 0);
      }

      if (hasTwoTextures && textures[1]) {
        // 绑定纹理 1
        gl.activeTexture(gl.TEXTURE1);
        gl.bindTexture(gl.TEXTURE_2D, textures[1]);
        // 设置着色器中的u_image1统一变量为纹理单元1
        gl.uniform1i(wrapper.u_image1, 1);
      }

      // 绑定缓冲区
      if (buffers) {
        gl.bindBuffer(gl.ARRAY_BUFFER, buffers);
        gl.enableVertexAttribArray(wrapper.a_position);
        gl.enableVertexAttribArray(wrapper.a_texCoord);
        gl.vertexAttribPointer(wrapper.a_position, 3, gl.FLOAT, false, 5 * Float32Array.BYTES_PER_ELEMENT, 0);
        // 纹理坐标属性，每个顶点 2 个分量，偏移 3 个浮点数
        gl.vertexAttribPointer(
          wrapper.a_texCoord,
          2,
          gl.FLOAT,
          false,
          5 * Float32Array.BYTES_PER_ELEMENT,
          3 * Float32Array.BYTES_PER_ELEMENT
        );
      }

      // 片元着色阈值
      gl.uniform1fv(wrapper.thresholds, thresholds);
      // 片元着色器颜色和
      gl.uniform1fv(wrapper.colors, colors);

      if (hasTwoTextures && animationNeed) {
        const nextFactor = animationFactor + 0.008;
        if (nextFactor <= 1) {
          animationFactor = nextFactor;
          // console.log(animationFactor + "g更新中");
        } else {
          // console.log(animationFactor + "达到上限，保持当前状态");
        }
      } else {
        animationFactor = 0;
        // console.log(animationFactor + "结束");
        animationNeed = false;
      }
      gl.uniform1i(wrapper["thresholdsStart"], thresholdsStart);
      gl.uniform1i(wrapper["thresholdsEnd"], thresholdsEnd);
      // 设置动画因子
      gl.uniform1f(wrapper.factor, animationFactor);
      gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
    }
  };

  addLayer(getLayerManagerState(map), layer);
}
// 加载雷达
export async function loadRadar(map: any, id: string, url: string, coordinate: any) {
  await getCanvas(url).then(() => {
    // radar layer 不存在则创建
    if (!layer) {
      initLayer(map, id, coordinate);
    }
    console.log("更新radar图层！");
  });
}
// 获取canvas
export async function getCanvas(tifUrl: string) {
  try {
    const canvas = await getCanvasByTiff(tifUrl);
    if (canvas == null) {
      console.log("canvas is null");
      return;
    }
    // 始终保持 canvasData只有一组数据或者两组数据
    if (canvasData.length > 2) {
      canvasData.shift();
    }
    canvasData.push(canvas);
    animationFactor = 0;
    animationNeed = true;
  } catch (error) {
    console.error("获取canvas时出错:", error);
  }
}
// // 添加图层
// addLayer: function () { },
// 移除图层
export function removeRadar(map: any, id: string) {
  if (layer) {
    // map.removeLayer(id);
    removeLayer(getLayerManagerState(map), id);
    // 清除资源
    canvasData = [];
    textures = [];
    // 动画因子
    animationFactor = 0.0;
    // 动画轮播
    animationNeed = true;
    buffers = [];
  }
}
// 设置阈值
export function setThresholds(thresholds: any) {
  thresholdsStart = thresholds[0];
  thresholdsEnd = thresholds[1];
}
